package com.ruoyi.different.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileTypeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.different.domain.DifferentConut;
import com.ruoyi.different.domain.DifferentLogging;
import com.ruoyi.different.domain.DifferentRete;
import com.ruoyi.different.service.IDifferentLoggingService;
import com.ruoyi.different.service.IDifferentReteService;
import com.ruoyi.framework.config.ServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 异网数据Controller
 * 
 * @author rocky
 * @date 2023-12-13
 */
@RestController
@RequestMapping("/different/rete")
public class VxDifferentReteController extends BaseController
{

    private static final String FILE_ZIP="zip";
    private static final String FILE_XLS=".xls";
    private static final String FILE_XLSX=".xlsx";
    private static final String FILE_PNG=".png";
    private static final String FILE_JPG=".jpg";
    private static final String FILE_JPEG=".jpeg";
    @Autowired
    private IDifferentReteService differentReteService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IDifferentLoggingService differentLoggingService;

    /**
     * 查询异网数据列表
     */
   // @PreAuthorize("@ss.hasPermi('different:rete:list')")
    @GetMapping("/list/vx")
    public TableDataInfo list(DifferentRete differentRete)
    {
        startPage();
        List<DifferentRete> list = differentReteService.selectDifferentReteList(differentRete);
        return getDataTable(list);
    }

    /**
     * 导出异网数据列表
     */
   // @PreAuthorize("@ss.hasPermi('different:rete:export')")
    @Log(title = "异网数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export/vx")
    public void export(HttpServletResponse response, DifferentRete differentRete)
    {
        List<DifferentRete> list = differentReteService.selectDifferentReteList(differentRete);
        ExcelUtil<DifferentRete> util = new ExcelUtil<DifferentRete>(DifferentRete.class);
        util.exportExcel(response, list, "异网数据数据");
    }

    /**
     * 获取异网数据详细信息
     */
   // @PreAuthorize("@ss.hasPermi('different:rete:query')")
    @GetMapping(value = "/vx/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(differentReteService.selectDifferentReteById(id));
    }

    /**
     * 新增异网数据
     */
    //@PreAuthorize("@ss.hasPermi('different:rete:add')")
    @Log(title = "异网数据", businessType = BusinessType.INSERT)
    @PostMapping("/vx")
    public AjaxResult add(@RequestBody DifferentRete differentRete)
    {
        Long aLong = differentReteService.insertDifferentRete(differentRete);
        return AjaxResult.success(aLong);
    }

    /**
     * 修改异网数据
     */
   // @PreAuthorize("@ss.hasPermi('different:rete:edit')")
    @Log(title = "异网数据", businessType = BusinessType.UPDATE)
    @PutMapping("/vx")
    public AjaxResult edit(@RequestBody DifferentRete differentRete)
    {
        return toAjax(differentReteService.updateDifferentRete(differentRete));
    }

    /**
     * 删除异网数据
     */
   // @PreAuthorize("@ss.hasPermi('different:rete:remove')")
    @Log(title = "异网数据", businessType = BusinessType.DELETE)
	@DeleteMapping("/vx/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(differentReteService.deleteDifferentReteByIds(ids));
    }

    @PostMapping("/upload/vx")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        if (!checkFileType(file)){
            return AjaxResult.error("文件格式错误");
        }
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
    //手机号查重
    //@PreAuthorize("@ss.hasPermi('different:rete:query')")
    @PostMapping(value = "/selectByPhone/vx")
    public AjaxResult selectByPhone(@RequestBody DifferentRete differentRete)
    {
        return success(differentReteService.selectByPhone(differentRete));
    }


    //转化次数接口

    @GetMapping("/listCount/vx")
    public Map<Integer, Long> listCount(DifferentRete differentRete)
    {
        List<DifferentRete> list = differentReteService.selectDifferentReteList(differentRete);
        Map<Integer, Long> collect = list.stream().collect(Collectors.groupingBy(DifferentRete::getFollowupTimes, Collectors.counting()));
        LinkedHashMap<Integer, Long> objectObjectLinkedHashMap = new LinkedHashMap<>();
        collect.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x->objectObjectLinkedHashMap.put(x.getKey(),x.getValue()));
        return objectObjectLinkedHashMap;
    }

    //统计接口
    @PostMapping(value = "/countStatistics/vx")
    public AjaxResult countStatistics(@RequestBody DifferentConut differentConut)
    {
        ArrayList<Map<String, Object>> maps = new ArrayList<>();
        //商机新增
        QueryWrapper<DifferentRete> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Objects.nonNull(differentConut.getBranchId()), DifferentRete::getBranchId, differentConut.getBranchId())
                .eq(Objects.nonNull(differentConut.getEntryClerk()), DifferentRete::getEntryClerk, differentConut.getEntryClerk())
                .ge(DifferentRete::getEntryTime, differentConut.getDateBegin())
                .le(DifferentRete::getEntryTime, differentConut.getDateEnd());
        List<DifferentRete> list = differentReteService.list(queryWrapper);
        //商机到期
        QueryWrapper<DifferentRete> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(Objects.nonNull(differentConut.getBranchId()), DifferentRete::getBranchId, differentConut.getBranchId())
                .eq(Objects.nonNull(differentConut.getEntryClerk()), DifferentRete::getEntryClerk, differentConut.getEntryClerk())
                .ge(DifferentRete::getMaturityTime, differentConut.getDateBegin())
                .le(DifferentRete::getMaturityTime, differentConut.getDateEnd());
        List<DifferentRete> list1 = differentReteService.list(queryWrapper1);
        //商机跟进
        QueryWrapper<DifferentLogging> queryWrapper2 = new QueryWrapper<>();
        DateTime datebeginfollow = DateUtil.offsetDay(differentConut.getDateBegin(), -1);
        DateTime dateendfollow = DateUtil.offsetDay(differentConut.getDateEnd(), 1);
        queryWrapper2.lambda().eq(Objects.nonNull(differentConut.getBranchId()),DifferentLogging::getAssociationId, differentConut.getBranchId())
                .eq(Objects.nonNull(differentConut.getEntryClerk()), DifferentLogging::getOperatorId,differentConut.getEntryClerk())
                .ge(DifferentLogging::getCreateTime, differentConut.getDateBegin())
                .le(DifferentLogging::getCreateTime, dateendfollow)
                .eq(DifferentLogging::getOrderStatu,4002);
        List<DifferentLogging> list2 = differentLoggingService.list(queryWrapper2);

        //商机转化
        QueryWrapper<DifferentRete> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.lambda().eq(Objects.nonNull(differentConut.getBranchId()), DifferentRete::getBranchId, differentConut.getBranchId())
                .eq(Objects.nonNull(differentConut.getEntryClerk()), DifferentRete::getEntryClerk, differentConut.getEntryClerk())
                .ge(DifferentRete::getConversionTime, differentConut.getDateBegin())
                .le(DifferentRete::getConversionTime, differentConut.getDateEnd());
        List<DifferentRete> list3 = differentReteService.list(queryWrapper3);


        DateTime dateBegin1= null;
        DateTime dateEnd1= null;
        //往前推
        if (Objects.nonNull(differentConut.getDateType())){
            if (differentConut.getDateType().equals("day")){
                 dateBegin1 = DateUtil.offsetDay(differentConut.getDateBegin(), -1);
                 dateEnd1 = DateUtil.offsetDay(differentConut.getDateEnd(), -1);
            }else if (differentConut.getDateType().equals("week")){
                dateBegin1 = DateUtil.offsetWeek(differentConut.getDateBegin(), -1);
                dateEnd1 = DateUtil.offsetWeek(differentConut.getDateEnd(), -1);
            }else if (differentConut.getDateType().equals("month")){
                dateBegin1= DateUtil.offsetMonth(differentConut.getDateBegin(), -1);
                dateEnd1 = DateUtil.offsetMonth(differentConut.getDateEnd(), -1);
            }else if (differentConut.getDateType().equals("custom")){
                HashMap<String, Object> map = new HashMap<>();
                map.put("dataType", "difAdd");
                HashMap<String, Object> map1 = new HashMap<>();
                map1.put("difNow", list.size());
                map1.put("difBefore",0);
                map.put("dataNum", map1);
                maps.add(map);

                HashMap<String, Object> mapa = new HashMap<>();
                mapa.put("dataType", "difDue");
                HashMap<String, Object> mapa1 = new HashMap<>();
                mapa1.put("difNow", list1.size());
                mapa1.put("difBefore", 0);
                mapa.put("dataNum", mapa1);
                maps.add(mapa);

                HashMap<String, Object> mapb = new HashMap<>();
                mapb.put("dataType", "difFollow");
                HashMap<String, Object> mapb1 = new HashMap<>();
                mapb1.put("difNow", list2.size());
                mapb1.put("difBefore", 0);
                mapb.put("dataNum", mapb1);
                maps.add(mapb);

                HashMap<String, Object> mapc = new HashMap<>();
                mapc.put("dataType", "difTrans");
                HashMap<String, Object> mapc1 = new HashMap<>();
                mapc1.put("difNow", list3.size());
                mapc1.put("difBefore", 0);
                mapc.put("dataNum", mapc1);
                maps.add(mapc);
                return AjaxResult.success(maps);
            }
        }
        //之前的数据
        //商机新增
        QueryWrapper<DifferentRete> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.lambda().eq(Objects.nonNull(differentConut.getBranchId()), DifferentRete::getBranchId, differentConut.getBranchId())
                .eq(Objects.nonNull(differentConut.getEntryClerk()), DifferentRete::getEntryClerk, differentConut.getEntryClerk())
                .ge(DifferentRete::getEntryTime, dateBegin1)
                .le(DifferentRete::getEntryTime,  dateEnd1);
        List<DifferentRete> list4 = differentReteService.list(queryWrapper4);
        //商机到期
        QueryWrapper<DifferentRete> queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.lambda().eq(Objects.nonNull(differentConut.getBranchId()), DifferentRete::getBranchId, differentConut.getBranchId())
                .eq(Objects.nonNull(differentConut.getEntryClerk()), DifferentRete::getEntryClerk, differentConut.getEntryClerk())
                .ge(DifferentRete::getMaturityTime,  dateBegin1)
                .le(DifferentRete::getMaturityTime,  dateEnd1);
        List<DifferentRete> list5 = differentReteService.list(queryWrapper5);
        //商机跟进
        QueryWrapper<DifferentLogging> queryWrapper6 = new QueryWrapper<>();
        DateTime datebeginfollow1 = DateUtil.offsetDay(dateBegin1, -1);
        DateTime dateendfollow1 = DateUtil.offsetDay(dateEnd1, 1);
        queryWrapper6.lambda().eq(Objects.nonNull(differentConut.getBranchId()),DifferentLogging::getAssociationId, differentConut.getBranchId())
                .eq(Objects.nonNull(differentConut.getEntryClerk()), DifferentLogging::getOperatorId,differentConut.getEntryClerk())
                .ge(DifferentLogging::getCreateTime,  dateBegin1)
                .le(DifferentLogging::getCreateTime,   dateendfollow1)
                .eq(DifferentLogging::getOrderStatu,4002);
        List<DifferentLogging> list6 = differentLoggingService.list(queryWrapper6);

        //商机转化
        QueryWrapper<DifferentRete> queryWrapper7 = new QueryWrapper<>();
        queryWrapper7.lambda().eq(Objects.nonNull(differentConut.getBranchId()), DifferentRete::getBranchId, differentConut.getBranchId())
                .eq(Objects.nonNull(differentConut.getEntryClerk()), DifferentRete::getEntryClerk, differentConut.getEntryClerk())
                .ge(DifferentRete::getConversionTime, dateBegin1)
                .le(DifferentRete::getConversionTime, dateEnd1);
        List<DifferentRete> list7 = differentReteService.list(queryWrapper7);

        HashMap<String, Object> map = new HashMap<>();
        map.put("dataType", "difAdd");
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("difNow", list.size());
        map1.put("difBefore", list4.size());
        map.put("dataNum", map1);
        maps.add(map);

        HashMap<String, Object> mapa = new HashMap<>();
        mapa.put("dataType", "difDue");
        HashMap<String, Object> mapa1 = new HashMap<>();
        mapa1.put("difNow", list1.size());
        mapa1.put("difBefore", list5.size());
        mapa.put("dataNum", mapa1);
        maps.add(mapa);

        HashMap<String, Object> mapb = new HashMap<>();
        mapb.put("dataType", "difFollow");
        HashMap<String, Object> mapb1 = new HashMap<>();
        mapb1.put("difNow", list2.size());
        mapb1.put("difBefore", list6.size());
        mapb.put("dataNum", mapb1);
        maps.add(mapb);

        HashMap<String, Object> mapc = new HashMap<>();
        mapc.put("dataType", "difTrans");
        HashMap<String, Object> mapc1 = new HashMap<>();
        mapc1.put("difNow", list3.size());
        mapc1.put("difBefore", list7.size());
        mapc.put("dataNum", mapc1);
        maps.add(mapc);

        return AjaxResult.success(maps);
    }

    public boolean checkFileType(MultipartFile file)  {
        String filename = file.getOriginalFilename();
        String fileType = filename.substring(filename.lastIndexOf("."));
        //先判断后缀名
        if (FILE_XLS.equalsIgnoreCase(fileType) || FILE_XLSX.equalsIgnoreCase(fileType)|| FILE_PNG.equalsIgnoreCase(fileType)|| FILE_JPG.equalsIgnoreCase(fileType)|| FILE_JPEG.equalsIgnoreCase(fileType)) {
            String type ;
            try {
                type = FileTypeUtil.getType(file.getInputStream());
                //根据首部字节判断文件类型
                if (FILE_ZIP.contains(type)||FILE_XLS.contains(type)||FILE_XLSX.contains(type)||FILE_PNG.contains(type)||FILE_JPG.contains(type)||FILE_JPEG.contains(type)){
                    return true;
                }
            } catch (Exception e) {
                logger.error("上传工作状态excel失败", e);

            }
            return true;

        }
        return false;
    }


}
